package com.example.anjia03_3z.service.impl;


import com.example.anjia03_3z.exception.ServiceException;
import com.example.anjia03_3z.mapper.ArticleContentMapper;
import com.example.anjia03_3z.mapper.ArticleMapper;
import com.example.anjia03_3z.pojo.dto.ArticleAddNewDTO;
import com.example.anjia03_3z.pojo.dto.ArticleContentAddNewDTO;
import com.example.anjia03_3z.pojo.entity.Article;
import com.example.anjia03_3z.pojo.entity.ArticleContent;
import com.example.anjia03_3z.pojo.vo.ArticleDetailVO;
import com.example.anjia03_3z.pojo.vo.ArticleListItemVO;
import com.example.anjia03_3z.security.AdminDetails;
import com.example.anjia03_3z.security.LoginPrincipal;
import com.example.anjia03_3z.service.IArticleService;
import com.example.anjia03_3z.web.ServiceCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 处理角色数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Value("${anjia.jwt.secret-key}")
    private String secretKey;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ArticleContentMapper articleContentMapper;

    @Override
    public void addArticle(ArticleAddNewDTO articleAddNewDTO) {
        //创建Article 实例
        Article article = new Article();
        //实例赋值
        Long id = getUserInfo().getId();
        article.setAdminId(id);
        BeanUtils.copyProperties(articleAddNewDTO, article);
        articleMapper.insertArticle(article);
    }

    @Override
    public ArticleDetailVO getArticleById(Long id) {
        return articleMapper.getArticle(id);
    }

    @Override
    public List<ArticleListItemVO> list() {
        return articleMapper.list();
    }

    public LoginPrincipal getUserInfo() {
        // 获取SpringSecurity上下文对象
        UsernamePasswordAuthenticationToken token =
                (UsernamePasswordAuthenticationToken)
                        SecurityContextHolder.getContext().getAuthentication();
        // 为了程序逻辑严谨,判断一下token是否为null
        if (token == null) {
            throw new ServiceException(
                    ServiceCode.ERR_UNKNOWN, "您还没有登录");
        }
        // 从SpringSecurity上下文对象中获取用户信息
        LoginPrincipal userInfo =
                (LoginPrincipal) token.getPrincipal();
        // 最终返回用户信息
        return userInfo;
    }

}
